﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;

namespace Examples
{
    /// <summary>
    /// Reads CamelotXml file using XmlDocument object
    /// </summary>
    class ReadCamelotXmlUsingXmlDocument
    {
        public static void DoIt(string xmlFile)
        {
            var xmlDocument = new XmlDocument();
            xmlDocument.Load(xmlFile);

            // read schema
            var schemaFields = xmlDocument.SelectNodes("List/Schema/Field");

            Console.WriteLine("Columns");

            if (xmlDocument.SelectSingleNode("List/Schema/Field/Type") != null)
            {
                //  full schema
                foreach (XmlNode field in schemaFields)
                    Console.WriteLine("  " + field.Attributes["Name"].Value + " (" + field.SelectSingleNode("DataType").InnerText + ", " + field.SelectSingleNode("Type").InnerText + ")");
            } else
            {
                // small schema
                foreach (XmlNode field in schemaFields)
                    Console.WriteLine("  " + field.Attributes["Name"].Value + " (" + field.SelectSingleNode("DataType").InnerText + ")");
            }

            // read content
            var contentRows = xmlDocument.SelectNodes("List/Content/Row").Cast<XmlNode>().ToList();
            foreach (XmlNode row in contentRows)
            {
                Console.WriteLine("Row #" + contentRows.IndexOf(row));

                foreach (XmlNode column in row.ChildNodes)
                {
                    if ((column as XmlElement).IsEmpty)
                    {
                        Console.WriteLine("  " + "NULL");
                    }
                    else
                    {
                        Console.WriteLine("  " + column.InnerText);                        
                    }                    
                }
            }
        }
    }
}
